package com.ruoyi.quality.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.sql.QueryHelp;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.quality.domain.*;
import com.ruoyi.quality.domain.dto.InspectionTaskTemplateSamplingItemDto;
import com.ruoyi.quality.domain.vo.InspectionTaskTemplateSamplingItemVo;
import com.ruoyi.quality.domain.vo.InspectionTaskValueVo;
import com.ruoyi.quality.mapper.InspectionTaskValueMapper;
import com.ruoyi.quality.service.InspectionTaskTemplateSamplingItemService;
import com.ruoyi.quality.mapper.InspectionTaskTemplateSamplingItemMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class InspectionTaskTemplateSamplingItemServiceImpl implements InspectionTaskTemplateSamplingItemService{

    @Resource
    InspectionTaskTemplateSamplingItemMapper inspectionTaskTemplateSamplingItemMapper;

    @Resource
    InspectionTaskValueMapper inspectionTaskValueMapper;

    @Override
    public Page<InspectionTaskTemplateSamplingItemVo> getInspectionTaskTemplateSamplingItemByPage(InspectionTaskTemplateSamplingItemDto pageEntity) {
        MPJLambdaWrapper<InspectionTaskTemplateSamplingItem> wrapper = new MPJLambdaWrapper<InspectionTaskTemplateSamplingItem>()
                .selectAll(InspectionTaskTemplateSamplingItem.class)//查询user表全部字段
//                .selectAs( InspectionTemplate::getName, InspectionTemplateItemVo::getTemplateName )
                .selectAs(InspectionItem::getName, InspectionTaskTemplateSamplingItemVo::getInspectionItemName)
                .selectAs(InspectionItem::getTolerance,InspectionTaskTemplateSamplingItemVo::getTolerance)
                .selectAs(InspectionItem::getQualified, InspectionTaskTemplateSamplingItemVo::getQualified)
                .selectAs(InspectionItem::getFailurePattern, InspectionTaskTemplateSamplingItemVo::getFailurePattern)
                .selectAs(InspectionItem::getStandardToleranceOne,InspectionTaskTemplateSamplingItemVo::getStandardToleranceOne)
                .selectAs(InspectionItem::getStandardToleranceTwo,InspectionTaskTemplateSamplingItemVo::getStandardToleranceTwo)
                .selectAs(Sampling::getName, InspectionTaskTemplateSamplingItemVo::getSamplingName)
                //物料的公差的配置
                .selectAs(InspectionTemplateItemMaterial::getLowerToleranceOne, InspectionTaskTemplateSamplingItemVo::getLowerToleranceOne)
                .selectAs(InspectionTemplateItemMaterial::getUpperToleranceOne, InspectionTaskTemplateSamplingItemVo::getUpperToleranceOne)
                .selectAs(InspectionTemplateItemMaterial::getLowerToleranceTwo, InspectionTaskTemplateSamplingItemVo::getLowerToleranceTwo)
                .selectAs(InspectionTemplateItemMaterial::getUpperToleranceTwo, InspectionTaskTemplateSamplingItemVo::getUpperToleranceTwo)
                .selectAs(InspectionTemplateItemMaterial::getToleranceOneDesc, InspectionTaskTemplateSamplingItemVo::getToleranceOneDesc)
                .selectAs(InspectionTemplateItemMaterial::getToleranceTwoDesc, InspectionTaskTemplateSamplingItemVo::getToleranceTwoDesc)
                //代码修改提交
                .eq(InspectionTaskTemplateSamplingItem::getDelFlag, 0)
                .eq(InspectionTaskTemplateSamplingItem::getInspectionTaskId, pageEntity.getInspectionTaskId())
                .eq(InspectionTaskTemplateSamplingItem::getFillType, pageEntity.getFillType())
//                .eq(null != pageEntity.getInspectionTemplateId(), InspectionTemplateItem::getInspectionTemplateId,pageEntity.getInspectionTemplateId())
                .leftJoin(InspectionItem.class, on ->
                                on.eq(InspectionItem::getId, InspectionTaskTemplateSamplingItem::getInspectionItemId)
                                .ne(InspectionItem::getDelFlag, 1)
                        )
                .leftJoin(InspectionTemplateItemMaterial.class,
                        on -> on.eq(InspectionTemplateItemMaterial::getInspectionItemId, InspectionItem::getId)
                        .ne(InspectionTemplateItemMaterial::getDelFlag, 1)
                )
                .leftJoin(Sampling.class, on -> on.eq(Sampling::getId, InspectionTaskTemplateSamplingItem::getSamplingId)
                        .ne(Sampling::getDelFlag, 1)
                )
                .eq(InspectionTemplateItemMaterial::getMaterialCode,pageEntity.getMaterialCode())
                .orderByDesc(InspectionTemplateItem::getCreateTime);
        wrapper = QueryHelp.getPredicateEx(wrapper, InspectionTaskTemplateSamplingItem.class, pageEntity);
        Page<InspectionTaskTemplateSamplingItemVo> userList = inspectionTaskTemplateSamplingItemMapper.selectJoinPage(new Page<>(pageEntity.getCurrentPage(), pageEntity.getPageSize()),   InspectionTaskTemplateSamplingItemVo.class, wrapper);


        List<Long> inspectionTaskTemplateSamplingItemIds = userList.getRecords().stream().map(item -> item.getId()).collect(Collectors.toList());

        MPJLambdaWrapper<InspectionTaskValue> wrapper1 = new MPJLambdaWrapper<InspectionTaskValue>()
                .in(null != inspectionTaskTemplateSamplingItemIds && inspectionTaskTemplateSamplingItemIds.size() > 0, InspectionTaskValue::getInspectionTaskTemplateSamplingItemId, inspectionTaskTemplateSamplingItemIds)
                .ne(Sampling::getDelFlag, 1);
        List<InspectionTaskValue>  inspectionTaskValueVosQuery =  inspectionTaskValueMapper.selectJoinList(wrapper1);


        for(InspectionTaskTemplateSamplingItemVo vo : userList.getRecords()) {

            List<InspectionTaskValue> inspectionTaskValueVosTmp = inspectionTaskValueVosQuery.stream().filter(item -> item.getInspectionTaskTemplateSamplingItemId().equals(vo.getId())).collect(Collectors.toList());



            if(null != inspectionTaskValueVosTmp && inspectionTaskValueVosTmp.size() > 0) {
                List<InspectionTaskValueVo> inspectionTaskValueVos = new ArrayList<>();
                for(InspectionTaskValue inspectionTaskValue : inspectionTaskValueVosTmp) {
                    InspectionTaskValueVo inspectionTaskValueVo =  new InspectionTaskValueVo();
                    inspectionTaskValueVo.setId(inspectionTaskValue.getId());
                    inspectionTaskValueVo.setName(inspectionTaskValue.getName());
                    inspectionTaskValueVo.setLowerTolerance(inspectionTaskValue.getLowerTolerance());
                    inspectionTaskValueVo.setUpperTolerance(inspectionTaskValue.getUpperTolerance());
                    inspectionTaskValueVo.setValue(inspectionTaskValue.getValue());
                    inspectionTaskValueVo.setValue2(inspectionTaskValue.getValue2());
                    inspectionTaskValueVo.setType(inspectionTaskValue.getType());
                    inspectionTaskValueVos.add(inspectionTaskValueVo);
                    vo.setValueList(inspectionTaskValueVos);
                }
            } else {
                List<InspectionTaskValueVo> inspectionTaskValueVos = new ArrayList<>();
                Integer count = vo.getFillQty();
                for(Integer i = 0; i < count; i++) {
                    //公差1配置
                    Integer indexCount = i + 1;
                    if("是".equals(vo.getStandardToleranceOne())) {
                        InspectionTaskValueVo inspectionTaskValueVo =  new InspectionTaskValueVo();
                        inspectionTaskValueVo.setId((long)i + 10);
                        inspectionTaskValueVo.setName(vo.getToleranceOneDesc() + ":" + indexCount + "范围[" + vo.getLowerToleranceOne() + "-" + vo.getUpperToleranceOne() + "]" );
                        inspectionTaskValueVo.setLowerTolerance(vo.getLowerToleranceOne());
                        inspectionTaskValueVo.setUpperTolerance(vo.getUpperToleranceOne());
                        inspectionTaskValueVo.setValue("0");
                        inspectionTaskValueVo.setValue2("0");
                        inspectionTaskValueVo.setType("公差1");
                        inspectionTaskValueVos.add(inspectionTaskValueVo);

                    }
                    //公差2配置
                    if("是".equals(vo.getStandardToleranceTwo()))  {
                        InspectionTaskValueVo inspectionTaskValueVo =  new InspectionTaskValueVo();
                        inspectionTaskValueVo.setId((long)i + 20);
                        inspectionTaskValueVo.setName(vo.getToleranceTwoDesc() + ":" + indexCount + "范围[" + vo.getLowerToleranceTwo() + "-" + vo.getUpperToleranceTwo() + "]" );
                        inspectionTaskValueVo.setLowerTolerance(vo.getLowerToleranceTwo());
                        inspectionTaskValueVo.setUpperTolerance(vo.getUpperToleranceTwo());
                        inspectionTaskValueVo.setValue("0");
                        inspectionTaskValueVo.setValue2("0");
                        inspectionTaskValueVo.setType("公差2");
                        inspectionTaskValueVos.add(inspectionTaskValueVo);
                    }
                }
                vo.setValueList(inspectionTaskValueVos);
            }
        }

        return userList;
    }

    @Override
    public void fillInspectionTaskValue(List<InspectionTaskTemplateSamplingItemDto> inspectionTaskTemplateSamplingItemDtos) {
        String userName = SecurityUtils.getUsername();
        List<Long> ids = new ArrayList<>();
        ids = inspectionTaskTemplateSamplingItemDtos.stream().map(item -> item.getId()).distinct().collect(Collectors.toList());
        MPJLambdaWrapper<InspectionTaskTemplateSamplingItem> wrapper = new MPJLambdaWrapper<InspectionTaskTemplateSamplingItem>()
                .in(InspectionTaskValue::getId, ids)
                .eq(InspectionTaskValue::getDelFlag, 0);
        List<InspectionTaskTemplateSamplingItem>  inspectionTaskValues =    inspectionTaskTemplateSamplingItemMapper.selectList(wrapper);
        for(InspectionTaskTemplateSamplingItem inspectionTaskTemplateSamplingItem: inspectionTaskValues) {
            Optional<InspectionTaskTemplateSamplingItemDto> optionalInspectionTaskValueDto = inspectionTaskTemplateSamplingItemDtos.stream().filter(item ->inspectionTaskTemplateSamplingItem.getId() == item.getId()).findFirst();
            if(optionalInspectionTaskValueDto.isPresent()) {
                InspectionTaskTemplateSamplingItemDto inspectionTaskValueDto = optionalInspectionTaskValueDto.get();
                inspectionTaskTemplateSamplingItem.setValue1(inspectionTaskValueDto.getValue1());
                inspectionTaskTemplateSamplingItem.setValue2(inspectionTaskValueDto.getValue2());
                inspectionTaskTemplateSamplingItem.setValue3(inspectionTaskValueDto.getValue3());
                inspectionTaskTemplateSamplingItem.setUpdateBy(userName);
                inspectionTaskTemplateSamplingItem.setUpdateTime(new Date());
                inspectionTaskTemplateSamplingItemMapper.updateById(inspectionTaskTemplateSamplingItem);
            }
        }
    }

    @Override
    public void copyInspectionTaskTemplateSamplingItem(InspectionTaskTemplateSamplingItemDto inspectionTaskTemplateSamplingItemDto) {
        InspectionTaskTemplateSamplingItem inspectionTaskTemplateSamplingItem = inspectionTaskTemplateSamplingItemMapper.selectById(inspectionTaskTemplateSamplingItemDto.getId());
        if(null == inspectionTaskTemplateSamplingItem) {
            throw new GlobalException("复制项不存在");
        }
        String userName = SecurityUtils.getUsername();

        inspectionTaskTemplateSamplingItem.setId(null);
        inspectionTaskTemplateSamplingItem.setCreateBy(userName);
        inspectionTaskTemplateSamplingItem.setCreateTime(new Date());
        inspectionTaskTemplateSamplingItemMapper.insert(inspectionTaskTemplateSamplingItem);
    }
}




